﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IterationLife.PlatformBackEnd.AppServices.Services;
using Util;
using Util.Exceptions;
using Util.Ui;
using Util.Webs.Mvc;
using Util.Webs.Security;

namespace IterationLife.PlatformBackEnd.WebSite.Controllers
{
    public class AuthenticationController : EasyUiControllerBase
    {
        /// <summary>
        /// 初始化安全认证控制器
        /// </summary>
        public AuthenticationController(IAuthenticationService iAuthenticationService)
        {
            AuthenticationService = iAuthenticationService;
        }

        /// <summary>
        /// 安全认证服务
        /// </summary>
        protected IAuthenticationService AuthenticationService { get; set; }

        [HttpGet]
        public ActionResult Login()
        {
            return View("Login");
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        [HttpPost]
        [FormExceptionHandler]
        public ActionResult Login(string userName, string password)
        {
            if (userName.IsEmpty())
                throw new Warning("用户名不能为空");
            if (password.IsEmpty())
                throw new Warning("密码不能为空");
            var userId = AuthenticationService.Login(userName, password);
            SecurityHelper.SignIn(userId);
            return Ok("登录成功");
        }

        /// <summary>
        /// 退出
        /// </summary>
        [HttpPost]
        [FormExceptionHandler]
        public ActionResult Logout()
        {
            SecurityHelper.SignOut();
            return Ok("退出成功");
        }
    }
}